package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.util.SmsCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author hjs
 */
@Service("userDetailsByPhonenumber")
public class UserDetailsByPhonenumberServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsByPhonenumberServiceImpl.class);

    @Autowired
    private ISysUserService userService;
    @Autowired
    private SmsCodeUtil smsCodeUtil;


    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByPhone(phoneNumber);
        SysUser registerUser = new SysUser();
        // 没有用户则注册
        if (StringUtils.isNull(user)) {
            // 注册用户
            registerUser.setPhonenumber(phoneNumber);
            registerUser.setUserName(phoneNumber);
            registerUser.setUserType("1");
            registerUser.setNickName("用户_" + phoneNumber.substring(7));
            registerUser.setPassword(SecurityUtils.encryptPassword(smsCodeUtil.getPwd(phoneNumber)));
            registerUser.setRoleIds(new Long[]{2L});
            boolean regFlag = userService.registerUser(registerUser);
            if (!regFlag) {
                throw new UsernameNotFoundException("注册用户失败");
            }
        }
        return createLoginUser(registerUser);
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

}

